#include <stdio.h>
#include <string.h>
#include "esp_http_client.h"
#include "sd_card.h"

#define FILE_URL "https://10.177.2.200:8000/cert.pem"
#define FILE_PATH "/sdcard/downloaded_file.txt"



static const char *svr_certificate =
"-----BEGIN CERTIFICATE-----\nMIID7zCCAtegAwIBAgIUQP95pWfBV2/8zNrcvVPFLx2EHAgwDQYJKoZIhvcNAQEL\
BQAwgYYxCzAJBgNVBAYTAkNOMQ4wDAYDVQQIDAVIZWJlaTERMA8GA1UEBwwITGFu\
Z2ZhbmcxDjAMBgNVBAoMBU5DSUFFMQwwCgYDVQQLDANKU0oxFTATBgNVBAMMDDEw\
LjE3Ny4yLjIwMDEfMB0GCSqGSIb3DQEJARYQc2hlbnRxbGZAMTYzLmNvbTAeFw0y\
NTAzMjQwODI0MTRaFw0yNjAzMjQwODI0MTRaMIGGMQswCQYDVQQGEwJDTjEOMAwG\
A1UECAwFSGViZWkxETAPBgNVBAcMCExhbmdmYW5nMQ4wDAYDVQQKDAVOQ0lBRTEM\
MAoGA1UECwwDSlNKMRUwEwYDVQQDDAwxMC4xNzcuMi4yMDAxHzAdBgkqhkiG9w0B\
CQEWEHNoZW50cWxmQDE2My5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\
AoIBAQDNIqHVKasdi9vN6SANPSqRvrsTsTzBumzAa5RQDOMLEd5BurzeUgz/BIt+\
HSVL3+MykzcmyLw3WPICYJqbfQ7C7w0SIcvOos/pBjW0xn7saZKxPy6KQ0/93Mgj\
zilQw/cYABhVmhmnaEFwvICsq0mGMqfGW0NkzyPvByMoBH/kxzBrr3OmsPvzNtpa\
UsOMoEpokEciPfqMdm0lbURF+SF0gbcyUjhScbn7CiDjhRxSG5YAW2uxlY87tVZt\
x4iNjiTKm8kYWdK8dmMB4eVnb6//5fM2C4tuvyHgvz9PMrmMKoJk67tDrd5MbmcP\
PhzLQZpZmy6xI1QMmDBRF5BMoxM9AgMBAAGjUzBRMB0GA1UdDgQWBBQJo4GkNZdI\
xK9WdMwMvJyiH2JR7TAfBgNVHSMEGDAWgBQJo4GkNZdIxK9WdMwMvJyiH2JR7TAP\
BgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQChw68GIlBWzSdfva2M\
wVHtZZdp0dcqOsvF8hZoqqkgap7N5lpMu8zP4ybbnKbZtHuTjsxpknZLkKQ81eaA\
AmNvaqooZQT5xKwQZe5caeBiMvcj8dxN6yO7Z4BzYHwYxZabPnFmC6P5frPkdUsW\
iADNjzVve3teJ83p6zdylHrXe/MxujoNCpR1V8kKBi5NanAgEvUILI0D+WM5ou6z\
0QcvxE1uL+sxXPklnEAwWtz1/9Jk7gh+nyPYfs23QZl3hrJzcmViWeKPrFGVJZpr\
yScsMk3ya3SuKi5sssXBF2THBm5UCNBcAze6tn2UBs6cd7FQplCkaGiPCgDncT86\
XemH\n-----END CERTIFICATE-----";

esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    switch(evt->event_id) {
        case HTTP_EVENT_ERROR:
            printf("HTTP_EVENT_ERROR\n");
            break;
        case HTTP_EVENT_ON_CONNECTED:
            printf("HTTP_EVENT_ON_CONNECTED\n");
            break;
        case HTTP_EVENT_HEADER_SENT:
            printf("HTTP_EVENT_HEADER_SENT\n");
            break;
        case HTTP_EVENT_ON_HEADER:
            printf("HTTP_EVENT_ON_HEADER, key=%s, value=%s\n", evt->header_key, evt->header_value);
            break;
        case HTTP_EVENT_ON_DATA:
            printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
            if (!esp_http_client_is_chunked_response(evt->client)) {
                // Write received data to a file
                FILE* f = fopen(FILE_PATH, "a");
                if (f == NULL) {
                    printf("Failed to open file for writing\n");
                    return ESP_FAIL;
                }
                fwrite(evt->data, 1, evt->data_len, f);
                fclose(f);
            }
            break;
        case HTTP_EVENT_ON_FINISH:
            printf("HTTP_EVENT_ON_FINISH\n");
            break;
        case HTTP_EVENT_DISCONNECTED:
            printf("HTTP_EVENT_DISCONNECTED\n");
            break;
    }
    return ESP_OK;
}

void download_file_task(void *pvParameters)
{
    esp_http_client_config_t config = {
        .url = FILE_URL,
        .event_handler = http_event_handler,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // Set up file to store the downloaded data
    FILE* f = fopen(FILE_PATH, "w");
    if (f == NULL) {
        printf("Failed to create file for writing\n");
        return;
    }
    fclose(f);

    esp_err_t err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        printf("File downloaded successfully\n");
    } else {
        printf("File download failed\n");
    }

    esp_http_client_cleanup(client);

    vTaskDelete(NULL);
}

void http_download_main()
{
    // Initialize SPIFFS file system (if necessary)

    xTaskCreate(&download_file_task, "download_file_task", 4096, NULL, 5, NULL);
}

